﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading.Tasks;

namespace SkypeTranslater.Windows
{
	/// <summary>
	/// Interaction logic for TranslateMailWindow.xaml
	/// </summary>
	public partial class TranslateMailWindow
	{
		public string OriginalText
		{
			get { return (string)GetValue(OriginalTextProperty); }
			set { SetValue(OriginalTextProperty, value); }
		}

		// Using a DependencyProperty as the backing store for OriginalText.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty OriginalTextProperty =
			DependencyProperty.Register("OriginalText", typeof(string), typeof(TranslateMailWindow), new UIPropertyMetadata(null));


		public string Translation
		{
			get { return (string)GetValue(TranslationProperty); }
			set { SetValue(TranslationProperty, value); }
		}

		// Using a DependencyProperty as the backing store for Translation.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty TranslationProperty =
			DependencyProperty.Register("Translation", typeof(string), typeof(TranslateMailWindow), new UIPropertyMetadata(null));

		public static RoutedCommand TranslateCommand = new RoutedCommand();

		public TranslateMailWindow()
		{
			InitializeComponent();
			this.CommandBindings.Add(new CommandBinding(TranslateCommand, TranslatedExecuted, (s, e) => e.CanExecute = txtOriginal.SelectedText != null
				&& txtOriginal.SelectedText.Length > 2));
			this.InputBindings.Add(new KeyBinding(TranslateCommand, new KeyGesture(Key.T, ModifierKeys.Control)));
			btnTranslate.Command = TranslateCommand;
		}

		void TranslatedExecuted(object sender, ExecutedRoutedEventArgs e)
		{
			e.Handled = true;
			var request = new TranslateServiceReference.TranslationRequest();
			request.FromLanguage = (cmbFromLang.SelectedItem as ComboBoxItem).Content as string;
			request.ToLanguage = (cmbToLang.SelectedItem as ComboBoxItem).Content as string;
			
			busyIndicator.IsBusy = true;
			
			Task task = new Task(new Action(() =>
			{
				using (SkypeTranslater.TranslateServiceReference.TranslateServiceClient client = new TranslateServiceReference.TranslateServiceClient())
				{
					var oper = this.Dispatcher.BeginInvoke(new Action(() =>
					{
						request.Content = txtOriginal.SelectedText;
					}), System.Windows.Threading.DispatcherPriority.Normal);
					oper.Wait();

					WeakReference weakRef = new WeakReference(new StringBuilder());

					var response = client.Translate(request);
					if (response != null)
					{
						this.Dispatcher.Invoke(new Action(() =>
						{
							Translation = response.TranslationResult;
						}), System.Windows.Threading.DispatcherPriority.Normal);
					}
				}
			}), TaskCreationOptions.LongRunning);
			task.Start();

			task.ContinueWith(prevTask =>
				{
					busyIndicator.IsBusy = false;
					prevTask.Dispose();
				}, System.Threading.CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());

			task.ContinueWith(prevTask =>
			{
				App.Log.Error("Error occurred while translatin email", prevTask.Exception);
				this.Dispatcher.Invoke(new Action(() =>
						{
							busyIndicator.IsBusy = false;
							MessageBox.Show(prevTask.Exception.Message);
						}));

				prevTask.Dispose();
			}, TaskContinuationOptions.NotOnRanToCompletion);

		}
	}
}
